package com.demo.myapplication.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.demo.myapplication.R;

public class FloatingService extends Service {

  private WindowManager windowManager;
  private View floatingView;

  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public int onStartCommand(Intent intent, int flag, int startId) {
    // add window
    Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
    showAlert();
    return START_STICKY;
  }

  private void showAlert() {
    if (windowManager == null || floatingView == null) {

      windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
      floatingView = View.inflate(getBaseContext(), R.layout.floating_layout, null);
      // do your stuff to update the view in layout
      WindowManager.LayoutParams params = new WindowManager.LayoutParams(
          WindowManager.LayoutParams.MATCH_PARENT,
          WindowManager.LayoutParams.MATCH_PARENT,
          WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
          WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE |
              WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
          PixelFormat.TRANSLUCENT);
      params.gravity = Gravity.CENTER | Gravity.CENTER;
      windowManager.addView(floatingView, params);
    }
  }

  @Override
  public void onCreate() {
    super.onCreate();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "end", Toast.LENGTH_SHORT).show();
    if (floatingView != null) windowManager.removeView(floatingView);
  }
}